package com.mryin.performance.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mryin.performance.common.Constant;
import com.mryin.performance.mapper.TaskMapper;
import com.mryin.performance.mapper.UserMapper;
import com.mryin.performance.pojo.Task;
import com.mryin.performance.pojo.User;
import com.mryin.performance.utils.PerformanceUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import static com.mryin.performance.utils.PerformanceUtils.*;

/**
 * @program: PerformanceManager
 * @description: 登录控制器
 * @author: Mr.YIN
 * @create: 2021-03-02 12:16
 **/
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String username, String password,
                          Model model, HttpSession session) {
        /*QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> eq = queryWrapper.eq("id", username).eq("password", password);
        User user = userMapper.selectOne(eq);
        if (user == null) {
            model.addAttribute("msg", "用户名或密码错误");
            return "login";
        } else {
            session.setAttribute("user", user);
            return "index";
        }*/
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","未知用户");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","*密码不正确*");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("msg","*账户已被锁定*");
            return "login";
        }catch (ExcessiveAttemptsException e){
            model.addAttribute("msg","*用户名或者是密码错误次数过多*");
            return "login";
        }catch (AuthenticationException e){
            model.addAttribute("msg","*用户名或者是密码不正确");
            return "login";
        }

        if(subject.isAuthenticated()){
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", username).eq("password", password));
            session.setAttribute("user",user);
            return "index";
        }else{
            usernamePasswordToken.clear();
            model.addAttribute("msg","*未知账户*");
            return "login";
        }
    }

    /**
     *  绩效管理的总结界面
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/toPerformanceIndex")
    public String toPerformanceIndex(Model model, HttpSession session) {
        Integer monovalentSum = 0;
        Integer marketpriceSum = 0;
        Double income;
        Double surplusValue;
        User user = (User) session.getAttribute("user");
        List<Task> allFinishTask = taskMapper.getAllFinishTask(user.getName());
        model.addAttribute("FinishTask", allFinishTask.size());
        List<Task> allUnFinishTask = taskMapper.getAllUnFinishTask(user.getName());
        model.addAttribute("UnFinishTask", allUnFinishTask.size());
        for (Task task : allFinishTask) {
            monovalentSum += task.getMonovalent();
            marketpriceSum += task.getMarketprice();
        }
        income = inCome(monovalentSum, user.getSalary(), Constant.WORK_DAY, taskMapper.getActualWorkDay());
        //model.addAttribute("income", income);
        model.addAttribute("income",new BigDecimal(income).setScale(2, RoundingMode.UP));
        surplusValue = surplusValue(marketpriceSum, income, (Constant.WORK_HOUR * taskMapper.getActualWorkDay()));
        //model.addAttribute("surplusValue", surplusValue);
        model.addAttribute("surplusValue", new BigDecimal(surplusValue).setScale(2, RoundingMode.UP));

        Integer rankingByNameOnSurplusValue = PerformanceUtils.valueComparatorBySurplusValue(user.getName(), userMapper, 0, 0, taskMapper);
        model.addAttribute("rankingByNameOnSurplusValue", rankingByNameOnSurplusValue);
        Integer rankingByNameOnIncome = PerformanceUtils.valueComparatorByInCome(user.getName(), userMapper, 0 , taskMapper);
        model.addAttribute("rankingByNameOnIncome", rankingByNameOnIncome);
        Integer rankingByNameOnMonovalent = null;
        Integer rankingByNameOnMarketPrice = null;
        try {
             rankingByNameOnMonovalent = taskMapper.getRankingByNameOnMonovalent(user.getName());
             rankingByNameOnMarketPrice = taskMapper.getRankingByNameOnMarketPrice(user.getName());
            if (0 == rankingByNameOnMonovalent && 0 == rankingByNameOnMarketPrice) {
                model.addAttribute("rankingByNameOnMonovalent", 0);
                model.addAttribute("rankingByNameOnMarketPrice", 0);
                return "page/performance/performanceIndex";
            }else{
                model.addAttribute("rankingByNameOnMonovalent", rankingByNameOnMonovalent);
                model.addAttribute("rankingByNameOnMarketPrice", rankingByNameOnMarketPrice);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("user", user);
        model.addAttribute("salary", user.getSalary());
        logger.info("我是单价总数==>" + monovalentSum);
        logger.info("我是底薪==>" + user.getSalary());
        logger.info("我是默认上班天数==>" + Constant.WORK_DAY);
        logger.info("我是默认上班时长，单位小时/天==>" + Constant.WORK_HOUR);
        logger.info("我是收入==>" + income);
        logger.info("我是市场总价==>" + marketpriceSum);
        logger.info("我是剩余价值==>" + surplusValue);
        logger.info("我是真实的工作天数==>" + taskMapper.getActualWorkDay());
        logger.info("我是绩效排名==>" + rankingByNameOnMonovalent);
        logger.info("我是市场价值排名==>" + rankingByNameOnMarketPrice);
        logger.info("我是剩余价值排名==>" + rankingByNameOnSurplusValue);
        logger.info("我是收入排名排名==>" + rankingByNameOnIncome);
        return "page/performance/performanceIndex";
    }
    @RequestMapping("/toPlanningTask")
    public String toPlanningTask(){
        return "page/task/planningTask";
    }

    @RequestMapping("/toPerformanceSetting")
    public String toPerformanceSetting(){
        return "page/task/performanceSetting";
    }


    @RequestMapping("/toTaskList")
    public String toTaskList(){
        return "page/task/unFinishTaskList";
    }

    @RequestMapping("/Finish/Performance")
    public String performanceFinish() {
        return "page/performance/finish";
    }

    @RequestMapping("/UnFinish/Performance")
    public String performanceUnFinish() {
        return "page/performance/unfinish";
    }

    @RequestMapping("/WaitFinish/Performance")
    public String performanceWaitFinish() {
        return "page/performance/waitFinish";
    }

    @RequestMapping("/OverTimeFinish/Performance")
    public String performanceOverTimeFinish() {
        return "page/performance/finish";
    }



    /**
     * 跳转到该编号的所显示页面
     * @return
     */
    @RequestMapping("/ToTransmitQRCode")
    public String toTransmitQRCode(){
        return "page/performance/QRCodeTransmit";
    }

    @RequestMapping("/loginout")
    public String loginout(HttpSession session) {
        session.removeAttribute("user");
        //session.invalidate();
        return "login";
    }
}
